<template>
  <div class="csup">
    <input type="file" ref="inputer" class="choosefile" @change="handleFileChange($event)" accept="image/*"/>
  </div>
</template>

<script>
  var myfiles
  import axios from 'axios'
  import {HOST} from '@/constants'

  export default {
    name: "wxupload",
    props: ['choosetype', 'uploadsucess'],
    data() {
      return {
        mloading:null,
        filePath: null,
        targetFile: null,
        imgurl: '',
        tempImgs: [],
        file: '',
        previewImg: {data: ''},
        ossupUrl: 'https://renshe.oss-cn-beijing.aliyuncs.com/',
      }
    },
    methods: {
      handleFileChange(e) {
        let inputDOM = this.$refs.inputer;
        this.targetFile = inputDOM;
        // 通过DOM取文件数据

        // this.file = inputDOM.files[0];
        this.file = e.target.files[0];
        myfiles = e.target.files[0];
        window.wfiles = e.target.files[0];
        window.tests="我是测试数据"
        console.log(this.file.name)
        console.log('-----------------------------------')
        this.errText = '';
        let size = Math.floor(this.file.size / 1024);

        if (size > 1024 * 6) {
          // 这里可以加个文件大小控制
          alert('上传文件不要超过6M')
          this.$refs.inputer.value = '';
          return false
        }
        var reader = new FileReader();
        reader.onload = (function (file) {
          return function (e) {
            // console.info(this.result); //这个就是base64的图标格式了
            window.base64Image = this.result
          };
        })(e.target.files[0]);
        reader.readAsDataURL(e.target.files[0])

        // 触发这个组件对象的input事件
        // this.$emit('input', this.file);
        // 这里就可以获取到文件的名字了
        this.fileName = this.file.name;

        console.log(window.base64Image)
        // alert(this.fileName)
        // 这里加个回调也是可以的
        // this.onChange && this.onChange(this.file, inputDOM.value);
        this.upload();
      },
      ossSign() {//签名
        console.log('57size:'+this.file.size)
        let tempFile = this.file
        let that = this;
        console.log('60size:'+tempFile.size)

          that.request.get('employees/getOssConfig',{token:'aa08769cdcb26674c6706093503ff0a3', cmloading: true}).then((res) => {
            console.log(res);
            // that.ossupUrl = res.data.host+'/'
            // resolve(res);
//            let inputDOM = this.$refs.inputer;
//
//            var smFile = inputDOM.files[0];
//            console.log(inputDOM)

            console.log('64size:'+window.tests)
            console.log('65size:----:'+tempFile.size)
            that.ossUpload(res);
          }, error => {
            setTimeout(() => {
              loading.close();
            }, 1000)

          })


      },
      ossUpload(sign) {//上传到阿里云
        let that = this;
        // console.log('size:75:' + temp.size)
        console.log('size:87:' + this.file)
        // console.log('size:88:' + window.base64Image)
        // console.log('size:89:' + that.file.size)

        function base64ToBlob(urlData) {
          var arr = urlData.split(','), mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
          while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
          }
          return new Blob([u8arr], { type: mime });
        }
        var newfiles = base64ToBlob(window.base64Image)

        let fileOfBlob = newfiles;
        console.log(fileOfBlob.size+'MMMMMMMMMMMMMMMMM')


        console.log('*****************')
        console.log(newfiles)
        console.log(newfiles.size)
        console.log('*****************')
          let data = {
            "key": "string",
            "name": "string",
            "type": "string",
            "vpath": "string"
          }
          /* eslint-disable no-undef */
          const instance = axios.create({
            timeout: 100000,
            headers: {'Content-Type': 'multipart/form-data'}
          })
          var last = that.file.name.split('.').length;
           //var chuo = new Date().getTime() + '.' + that.file.name.split('.')[1];
          //var chuo = new Date().getTime() + '.jpg'
        //获取文件的后缀名

        var lastIndex = that.file.name.lastIndexOf('.');
          var fileLength = that.file.name.length;
          var extName = that.file.name.substring(lastIndex, fileLength);
          var randm = Math.ceil(Math.random()*1000000)+'';
          var chuo = new Date().getTime() +randm+ extName;
          // alert(chuo)
          let param = new FormData()  // 创建form对象
          param.append('chunk', '0') // 添加form表单中其他数据
          param.append('OSSAccessKeyId', sign.data.accessid) // 添加form表单中其他数据
          param.append('policy', sign.data.policy) // 添加form表单中其他数据
          param.append('Signature', sign.data.signature) // 添加form表单中其他数据
          param.append('Expires', sign.data.expire) // 添加form表单中其他数据
          param.append('key', sign.data.dir + chuo) // 添加form表单中其他数据
          param.append('success_action_status', '200') // 添加form表单中其他数据
          param.append('success_action_statusText', 'ok') // 添加form表单中其他数据
          param.append('Access-Control-Allow-Origin', '*') // 添加form表单中其他数据
          param.append('file', fileOfBlob, chuo)  // 通过append向form对象添加数据
          console.log('.................')
          console.log('size:107：' + that.file.size) // FormData私有类对象，访问不到，可以通过get判断值是否传进去
          console.log('.................')

          // alert(chuo)
          // let config = {
          //   headers: {'Content-Type': 'multipart/form-data'}
          // }
          // 添加请求头
          // console.log(config);
          // axios.defaults.headers.post['Content-Type'] = 'multipart/form-data';
          instance.post(that.ossupUrl, param).then(response => {
            console.log(response)
            console.log('-----------------------------------')
            if (response.status == 200) {
              let rimg = {
                key: sign.data.dir + chuo,
                name: that.file.name
              }
              if(that.choosetype == 1 || that.choosetype == 2){
                that.uploadBoss(rimg)
              }else{
                that.upgs(rimg);
              }

              // that.$indicator.close()
              // that.$refs.inputer.value = '';
              // resolve(rimg);
            } else {
              // alert('sssssssssssssssss')
            }
          }, error => {
            console.log(JSON.stringify(error))

            setTimeout(() => {
              this.mloading.close();
            }, 1000)
          })

      },
      uploadBoss(img) {
        let that = this;
        var out_member_id = window.mid?window.mid:localStorage.getItem('out_members_id');
        var imgJson = {
          member_id: out_member_id, //window.mid,
          image_type: that.choosetype, //（1：正面，人头面，2：反面）
          card_url: that.ossupUrl + img.key, // oss全量地址
          cmloading: true
        }

        console.log('*****************************************************')
        console.log(imgJson)
        console.log('*****************************************************')


          that.request.post('employees/uploadimages', imgJson).then((sbdata) => {
            console.log('*****************************************************')
            console.log(JSON.stringify(sbdata))
            console.log('*****************************************************')
            if (sbdata.code == 0) {

              sbdata.type = this.choosetype
              sbdata.img = this.ossupUrl + sbdata.url
              this.$emit('uploadsucess', sbdata)
              setTimeout(() => {
                this.mloading.close();
              }, 200)

            } else {
              alert(sbdata.msg)
              if(that.choosetype==1){
                that.$refs.inputer.value=''
              }else{
                that.$refs.inputer.value=''
              }
              setTimeout(() => {
                this.mloading.close();
              }, 200)
            }
          }, error => {
            setTimeout(() => {
              this.mloading.close();
            }, 1000)

          })


      },
      upgs(sdata){

        sdata.type = this.choosetype
        // console.log(sdata)
        sdata.img = this.ossupUrl + sdata.key
        this.$emit('uploadsucess', sdata)
        setTimeout(() => {
          this.mloading.close();
      }, 1000)

      },
      upload() {


        let that = this;
        console.log('size:163:' + this.file.size)
       this.mloading = this.$loading({
          lock: true,
          text: '请稍后...',
          spinner: 'el-icon-loading',

        });


        console.log('189size:'+this.file.size)

        if (this.choosetype == 1 || this.choosetype == 2) {//身份证识别
          this.ossSign()

        }
        if (this.choosetype == 3) {//上传营业执照


           this.ossSign()

        }


      }
    }
  }
</script>

<style lang="scss" scoped>
  .choosefile {
    font-size: 200px;
    opacity: 0;
    position: absolute;
    width:100%;height:100%;
    z-index: 99;
    top: 0;
    left: 0;
  }

</style>
